let isInit = false
let audio
let analyser
let dataArr
export default function () {
    audio = document.getElementById("audio")
    audio.onplay = function (e) {
        isInit = true
        initSource()
    }
    audio.onpause = function (e) {
        console.log(e);
        isInit = false
    }
    draw()
}

function initSource() {
    //创建实例
    const context = new AudioContext();
    //获取音频上下文
    const source = context.createMediaElementSource(audio)
    //分析器节点
    analyser = context.createAnalyser()
    analyser.fftSize = 512
    //分析数据
    dataArr = new Uint8Array(512 / 2)
    source.connect(analyser)
    analyser.connect(context.destination)
}

function draw() {
    const canvas = document.getElementById("cans")
    const ctx = canvas.getContext("2d")
    requestAnimationFrame(draw)
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    //获取分析器节点
    if (!isInit) return
    analyser.getByteFrequencyData(dataArr)
    let len = dataArr.length
    let barWidth = canvas.width / len / 2
    let barHeight
    for (let i = 0; i < len; i++) {
        barHeight = (dataArr[i] / 255) * canvas.height
        let x1 = barWidth * i + canvas.width / 2
        let x2 = canvas.width / 2 - (i + 1) * barWidth
        let y = canvas.height - barHeight
        ctx.fillRect(x1, y, barWidth-1, barHeight)
        ctx.fillRect(x2, y, barWidth-1, barHeight)
        ctx.fillStyle = '#0e65c5';
    }
}

